<template>
  <div ref="chart" class="chart-container"></div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      chart: null,
      option: {
        title: {
          text: '害虫频率趋势图',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'cross'}
        },
        legend: {
          data: [],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',  // 为图例留出空间
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          data: []
        }],
        yAxis: [{
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        }],
        series: []
      }
    };
  },
  async mounted() {
    await this.fetchData();
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    async fetchData() {
      try {
        const response = await axios.get('http://localhost:8088/api/chart/pest-trend');
        console.log('API响应数据:', response.data);

        // 数据转换关键步骤
        this.option.xAxis[0].data = response.data.months;
        this.option.legend.data = response.data.series.map(item => item.name);

        this.option.series = response.data.series.map(item => ({
          name: item.name,
          type: 'line',
          stack: 'Total',  // 确保堆叠模式开启
          areaStyle: {
            opacity: 0.8  // 增加区域透明度
          },
          emphasis: {
            focus: 'series'
          },
          data: item.data,
          smooth: true  // 添加平滑曲线
        }));

        console.log('最终图表配置:', this.option);
      } catch (error) {
        console.error('数据获取失败:', error);
        // 可以添加用户可见的错误提示
      }
    },
    initChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
      }
      this.chart.setOption(this.option);

      // 调试用：检查实际渲染配置
      setTimeout(() => {
        const currentOption = this.chart.getOption();
        console.log('当前渲染配置:', currentOption);
      }, 500);
    },
    handleResize() {
      if (this.chart) {
        setTimeout(() => {
          this.chart.resize();
          console.log('图表已重绘');
        }, 300);
      }
    }
  }
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 600px; /* 增加高度 */
  min-width: 300px; /* 防止移动端过小 */
  background: #fff; /* 添加背景色 */
}
</style>
